import React from 'react'
import { TreeSelect} from 'antd';
const TreeNode = TreeSelect.TreeNode;
import api from '../../../api/area';

import './index.less'

export default class AreaTree extends React.Component {
  state = {
    treeData: [],
    loading: false,
  }

  componentDidMount = () =>{
    this.initData(this.props.pid || 1);
  }

  initData = (id) => {
    this.setState({ loading: true });
    api.get('/getAreaByParent', { id: id }).then((data) => {
      const result = data.data.data;

      this.setState({
        loading: false,
        treeData: result,
      });
    });
  }

  onChange = (value) => {
    this.setState({ value });
  }

  onLoadData = (treeNode) => {
    const _this = this;
    return new Promise((resolve) => {
      treeNode.props.dataRef.children = [];
      api.get('/getAreaByParent', { id: treeNode.props.dataRef.id }).then((data) => {
        const result = data.data.data;
        for(let i=0;i<result.length;i++){
          treeNode.props.dataRef.children.push(result[i]);
        }

        _this.setState({
          treeData: [...this.state.treeData],
        });
      });
      resolve();
    });
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} value={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} value={item.id} dataRef={item} />;
    });
  }

  render() {
    const treeNodes = this.renderTreeNodes(this.state.treeData);
    
    return (
      <TreeSelect
        showSearch
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        onChange={this.onChange}
        loadData={this.onLoadData}
        placeholder="请选择一个区域信息"
        defaultValue={this.props.defaultKey}
        allowClear
      >
        {treeNodes}
      </TreeSelect>
    );
  }
}